package dome_011;

import java.util.concurrent.TimeUnit;

/**
 * <p>Description: [ThreadLocal线程局部变量
 * ThreadLocal是使用空间换时间，synchronized是使用时间换空间
 * 比如在hibernate中session就存在与ThreadLocal中，避免synchronized的使用
 * <p>
 * 运行下面的程序，理解ThreadLocal
 * ThreadLocal只对当前线程范围有效。]</p>
 * Created on 2020/12/14
 *
 * @author <a href="mailto: 819712047@qq.com">谢振东 </a>
 * @version 1.0
 */
public class ThreadLocal2 {

    private static ThreadLocal<Person1> tl = new ThreadLocal<>();

    public static void main(String[] args) {

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "已启动");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "睡眠结算");
            System.out.println(tl.get());
        }, "Thread1").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "已启动");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "睡眠结算");
            tl.set(new Person1());
        }, "Thread2").start();
    }
}

class Person1 {
    String name = "zhangsan";

    @Override
    public String toString() {
        return "Person1{" +
                "name='" + name + '\'' +
                '}';
    }
}
